<template>
  <div>
    <el-card>
      <el-form ref="form" :model="form" class="form" :inline="true" size="mini">
        <el-form-item label="名称:" class="name">
          <el-input
            v-model="form.name"
            @change="getOMOUser()"
            clearable
            style="width: 200px"
          ></el-input>
        </el-form-item>
        <el-form-item label="行业:">
          <el-col :span="24">
            <el-select v-model="form.type1" placeholder="请选择">
              <el-option
                v-for="item in tableData"
                :key="item.id"
                :label="item.type1"
                :value="item.type1"
              >
              </el-option>
            </el-select>
            <span>-</span>
            <el-select v-model="form.type2" placeholder="请选择">
              <el-option
                v-for="item in tableData"
                :key="item.id"
                :label="item.type2"
                :value="item.type2"
              >
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <div class="buttonL">
          <el-button type="primary" size="small" @click="query">查询</el-button>
          <el-button size="small" @click="resetForm">重置</el-button>
        </div>
      </el-form>
      <el-button type="primary" size="small" @click="dialogVisible = true"
        >添加素材</el-button
      >
    </el-card>
    <el-card>
      <el-table border :data="tableData" row-key="id">
        <el-table-column sortable label="素材名称" prop="name" align="center" />
        <el-table-column sortable label="素材库" prop="img" align="center">
          <template slot-scope="{ row }">
            <img
              :src="row.img"
              style="
                border-radius: 50%;
                width: 100px;
                height: 100px;
                padding: 10px;
              "
              alt=""
              @click="showQrCode(row.img)"
            />
          </template>
        </el-table-column>
        <el-table-column label="素材类别" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.type1 }}</span
            >-<span>{{ scope.row.type2 }}</span>
          </template>
        </el-table-column>
        <el-table-column sortable label="价格" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.price }}</span
            >元
          </template>
        </el-table-column>
        <el-table-column sortable label="上传日期" prop="time" align="center">
          <template slot-scope="{ row }">
            {{ row.time | formatDate }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="reWriteOMOUser(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              @click="delOMOUser(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="page.page"
        :page-size="page.size"
        :page-sizes="[2, 3, 5, 10]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @current-change="changePage"
        @size-change="changeSize"
      />
    </el-card>
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="50%"
      @close="close"
    >
      <el-form
        ref="ruleForm"
        :model="formData"
        label-width="80px"
        :rules="rules"
      >
        <el-form-item label="素材名称" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="行业" prop="type1">
          <el-input v-model="formData.type1"></el-input>
        </el-form-item>
        <el-form-item label="子行业" prop="type2">
          <el-input v-model="formData.type2"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model.number="formData.price"></el-input>
        </el-form-item>
        <el-form-item label="时间日期" prop="time">
          <el-date-picker
            v-model.number="formData.time"
            align="right"
            type="date"
            placeholder="选择日期"
            :picker-options="pickerOptions"
            value-format="timestamp"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="图片" prop="img">
          <!-- <el-input v-model="formData.img"></el-input> -->
          <image-upload ref="myStaffPhoto" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="btnOK('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="二维码"
      :visible.sync="showCodeDialog"
      @opened="showQrCode"
      @close="imgUrl = ''"
    >
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import {
  getOMOUser,
  searchOMOUser,
  reWriteOMOUser,
  addOMOUser,
  delOMOUser,
  getOMOTotal,
  reWriteOMOTotal
} from '@/api/OfficialML.js'
import { queryFn } from '@/utils'
import QrCode from 'qrcode'
export default {
  data () {
    var checkImg = (rule, value, callback) => {
      if (!this.$refs.myStaffPhoto.fileList[0]) {
        return callback(new Error('图片不能为空'))
      } else {
        callback()
      }
    }
    return {
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [
          {
            text: '今天',
            onClick (picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: '昨天',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '一周前',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      // 弹窗显示控制
      dialogVisible: false,
      showCodeDialog: false,
      // 表格数据
      tableData: [],
      // 验证规则
      rules: {
        name: [
          { required: true, message: '请输入素材名称', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur'
          }
        ],
        type1: [
          { required: true, message: '请输入行业名称', trigger: 'blur' },
          { min: 1, max: 8, message: '长度在 1 到 8 个字符', trigger: 'blur' }
        ],
        type2: [
          { required: true, message: '请输入子行业名称', trigger: 'blur' },
          { min: 1, max: 8, message: '长度在 1 到 8 个字符', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '价格不能为空' },
          { type: 'number', message: '价格必须为数字值' }
        ],
        time: [{ required: true, message: '时间不能为空' }],
        img: [{ validator: checkImg, trigger: 'blur' }]
      },
      // 翻页
      currentPage: 1,
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      // 查询数据
      form: {
        name: '',
        type1: null,
        type2: null
      },
      formData: {}
    }
  },
  methods: {
    // 搜索功能
    async query () {
      const obj = queryFn(this.form)
      const { data } = await searchOMOUser(obj)
      console.log(data)
      this.tableData = data
      this.page.total = data.length
    },
    // 重置表单
    resetForm () {
      this.form.name = ''
      this.form.type1 = null
      this.form.type2 = null
      this.getOMOUser()
    },
    // 翻页
    changePage (newPage) {
      this.page.page = newPage
      const obj = {
        _page: this.page.page,
        _limit: this.page.size
      }
      this.getOMOUser(obj)
    },
    // 变换页面条数
    changeSize (newSize) {
      this.page.size = newSize
      const obj = {
        _limit: this.page.size
      }
      this.getOMOUser(obj)
    },
    // 获取店铺信息
    async getOMOUser (obj) {
      const { data } = await getOMOUser(obj)
      this.tableData = data
      const res = await getOMOTotal()
      this.page.total = res.data[0].total
    },
    // 获取id为？的信息并渲染到弹窗上
    async reWriteOMOUser (id) {
      try {
        this.dialogVisible = true
        const { data } = await searchOMOUser({ id: id })
        this.formData = data[0]
        if (this.formData.staffPhoto) {
          this.$refs.myStaffPhoto.fileList = [
            { url: this.formData.staffPhoto, upload: true }
          ]
        }
        // console.log(this.formData)
      } catch (error) {
        console.log(error)
      }
    },
    // 提交修改
    async btnOK (ruleForm) {
      if (this.formData.id) {
        const fileList = this.$refs.myStaffPhoto.fileList
        if (fileList.some((item) => !item.upload)) {
          //  如果此时去找 upload为false的图片 找到了说明 有图片还没有上传完成
          this.$message.warning('您当前还有图片没有上传完成！')
          return
        }
        this.$refs[ruleForm].validate(async (success) => {
          if (success) {
            this.formData.img =
            fileList && fileList.length ? fileList[0].url : ''
            await reWriteOMOUser(this.formData)
            this.$message.success('修改成功!')
            this.getOMOUser()
            this.changeSize(this.page.size)
            this.changePage(this.page.page)
            this.formData = {}
            this.dialogVisible = false
          } else {
            return false
          }
        })
      }
      this.$refs[ruleForm].validate(async (success) => {
        if (success) {
          const fileList = this.$refs.myStaffPhoto.fileList
          if (fileList.some((item) => !item.upload)) {
            //  如果此时去找 upload为false的图片 找到了说明 有图片还没有上传完成
            this.$message.warning('您当前还有图片没有上传完成！')
            return
          }
          this.formData.img =
              fileList && fileList.length ? fileList[0].url : ''
          await addOMOUser(this.formData)
          const obj = {
            id: 1,
            total: this.page.total + 1
          }
          await reWriteOMOTotal(obj)
          this.$message.success('添加成功!')
          this.$refs.myStaffPhoto.handleRemove(this.$refs.myStaffPhoto.fileList[0])
          this.getOMOUser()
          this.changeSize(this.page.size)
          this.changePage(this.page.page)
          this.formData = {}
          this.dialogVisible = false
        } else {
          return false
        }
      })
    },
    showQrCode (url) {
      // url存在的情况下 才弹出层
      if (url) {
        this.showCodeDialog = true // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
        // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
        this.$nextTick(() => {
          // 此时可以确认已经有ref对象了
          QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化成二维码
          // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
        })
      }
    },
    close () {
      this.dialogVisible = false
      this.$refs.ruleForm.resetFields()
      this.$refs.myStaffPhoto.handleRemove(this.$refs.myStaffPhoto.fileList[0])
      this.formData = {}
    },
    async delOMOUser (id) {
      try {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            await delOMOUser(id)
            this.$message.success('删除成功!')
            const obj = {
              id: 1,
              total: this.page.total - 1
            }
            await reWriteOMOTotal(obj)
            this.getOMOUser()
          })
          .catch(() => {})
      } catch (error) {
        this.$message.error('删除失败,请重试!')
      }
    }
  },
  created () {
    this.getOMOUser()
    this.changeSize(this.page.size)
  }
}
</script>

<style lang="less" scoped>
.form {
  box-sizing: border-box;
}
.el-row {
  padding-left: 20px;
  margin-top: 20px;
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.buttonL {
  padding-left: 30px;
  display: inline-block;
  margin-left: 30px;
}
</style>
